package com.polidea.rxohosble2.internal.util;


import bleshadow.javax.inject.Inject;
import bleshadow.javax.inject.Named;

import com.polidea.rxohosble2.ClientComponent;
import com.polidea.rxohosble2.ClientScope;
import ohos.app.Context;
import ohos.os.ProcessManager;

@ClientScope
public class CheckerLocationPermission {

    private final Context context;
    private final String[] scanPermissions;

    @Inject
    CheckerLocationPermission(
            Context context,
            @Named(ClientComponent.PlatformConstants.STRING_ARRAY_SCAN_PERMISSIONS) String[] scanPermissions
    ) {
        this.context = context;
        this.scanPermissions = scanPermissions;
    }

    public boolean isScanRuntimePermissionGranted() {
        for (String locationPermission : scanPermissions) {
            if (isPermissionGranted(locationPermission)) {
                return true;
            }
        }
        return scanPermissions.length == 0;
    }

    public String[] getRecommendedScanRuntimePermissions() {
        return scanPermissions;
    }

    /**
     * Copied from ohos.support.v4.content.ContextCompat for backwards compatibility
     * @param permission the permission to check
     * @return true is granted
     */
    private boolean isPermissionGranted(String permission) {
        if (permission == null) {
            throw new IllegalArgumentException("permission is null");
        }

//        return context.verifyPermission(permission, ProcessManager.getPid(), ProcessManager.getUid()) == PackageManager.PERMISSION_GRANTED;//暂无支持PackageManager.PERMISSION_GRANTED，可以寻找其他方案替代
        return context.verifyPermission(permission, ProcessManager.getPid(), ProcessManager.getUid()) == 0;//为了编译通过PackageManager.PERMISSION_GRANTED暂时写个0
    }
}
